import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { has, isObject } from 'lodash';
import classNames from 'classnames';

import DirectoryTree from '../components/directory-tree.jsx';
import DirectoryPlaceholder from '../components/directory-placeholder.jsx';
import TreeViewContextMenu from '../components/tree-view-context-menu.jsx';

import { loadDirectory, collapseDirectory, expandDirectory } from '../actions/directory-actions.js';
import { switchActiveFile, openFile, createDir,
    createFile, deletePath, movePath } from '../actions/files-actions.js';
import { showPathInputBar } from '../actions/path-input-bar-actions.js';
import { showConfirmDeleteDialog } from '../actions/confirm-delete-dialog-actions.js';

/**
 * 获得当前选中文件路径
 * @param  {Object[]} filesOpened
 * @param  {number}   index
 * @return {string}
 */
function getActivePath(filesOpened, index) {
    const match = filesOpened[index];
    return isObject(match) ? match.path : '';
}

/**
 * 处理目录展开/关闭
 * @param  {string}  path
 * @param  {bool}    isCollapsed
 * @return {Object}
 */
function handleToggleCollapse(path, isCollapsed = false) {
    if (isCollapsed) {
        return expandDirectory(path);
    }
    return collapseDirectory(path);
};

/**
 * 左侧文件树型边栏
 * @class {TreeView}
 * @extends {React.Component}
 */
@connect(state => ({
    directory: state.directory,
    files: state.files
}))
export default class TreeView extends Component {

    componentWillMount() {
        const { dispatch } = this.props;

        return dispatch(loadDirectory());
    }

    render() {
        const { directory, files, dispatch } = this.props;
        const boundTreeActions = bindActionCreators({
            handleOpenFile: openFile,
            handleToggleCollapse
        }, dispatch);
        const boundContextActions = bindActionCreators({
            createDir,
            createFile,
            movePath,
            deletePath,
            showPathInputBar,
            showConfirmDeleteDialog
        }, dispatch);
        const activePath = getActivePath(files.opened, files.current);

        return (
            <div className="tree-view">
                <DirectoryTree
                    tree={directory.tree}
                    expanded={directory.expanded}
                    activePath={activePath}
                    {...boundTreeActions} />
                <DirectoryPlaceholder
                    renderTag="footer"
                    attributes={{
                        className: 'directory-placeholder'
                    }} />
                <TreeViewContextMenu
                    {...boundContextActions} />
            </div>
        );
    }
}